<?php 
require_once "../../sys/config.php";
require_once PATH_DB_MAIN."utility.php";


abstract class ServiceProvider{
	protected $url;
	protected $stockDataType;
	protected $hasTick;
	protected $dataExported;
	
	//variabili di sessione
	protected $records;
	protected $localFileName;
	protected $backupPathFileName;
	
	abstract public function GetStockExchangeTickers($SEname);
	abstract public function GetStockData($ticker, $ts);
	abstract public function FormatData($record);
	
	public function BeginStockRead($stockName, $timestamp, $tsSkip = NULL, $cntSkip = NULL){
		$lineCntRet = 0;
		$dayReq = date('Ymd', strtotime("@".$timestamp));
		$this->localFileName = $this->FileName($stockName, $timestamp);
		$this->backupPathFileName = PATH_PROVIDER_BACKUP;
		$this->backupPathFileName .= $this->GetBackupFileName($this->localFileName);
		
		if(date('Ymd') == $dayReq){		// si riferisce ad oggi...
			//TODO
		}
		else{							// si riferisce al passato...
			if(file_exists($this->backupPathFileName) === false){	// se non e' mai stato fatto un backup:
				//1. legge dal provider
				$fContent = file_get_contents($this->GetStockQueryString($stockName, $timestamp));
				//2. salva su file di testo
				file_put_contents(PATH_PROVIDER.$this->localFileName, $fContent);
				//3. crea backup
				create_zip(PATH_PROVIDER.$this->localFileName, $this->backupPathFileName);
				echo "<br>$this->backupPathFileName created.";
			}
			else{								//...altrimenti ripristina dal backup
				if($this->IsLocalFileEmpty(PATH_PROVIDER.$this->localFileName)){
					extract_zip($this->backupPathFileName);
					echo "<br>$this->backupPathFileName extracted.";
				}
			}
			
			// legge il file di testo
			$lineCntRet = $this->GetHeaderAndRecords(PATH_PROVIDER.$this->localFileName, $tsSkip, $cntSkip);
		}
		
		return $lineCntRet;
	}
	
	public function GetStockDataType(){
		return $this->stockDataType;
	}
	
	public function HasTickData(){
		return $this->hasTick;
	}
	
	public function GetNextData(){
		//$this->LocalFileDeleteRecord($this->localFileName, 0);
		return $this->FormatData(array_shift($this->records));
	}
	
	public function EndStockRead(){
		//TODO cancella il file locale...
	}

	abstract protected function GetStockQueryString($ticker, $ts);
	abstract protected function GetExchangeQueryString($SEname);
	abstract protected function GetBackupFileName($fName);
	abstract protected function GetHeaderAndRecords($fName, $tsSkip = NULL, $cntSkip = NULL);
	abstract protected function IsLocalFileEmpty();
	//abstract public function LocalFileRecordCount();	//TODO rendere protected
	abstract protected function LocalFileDeleteRecord($nRec);
	
	private function FileName($stockName, $ts){
		return $stockName."_".date("Ymd", $ts).".txt";
	}
	
	private function CreateBackup($stockName, $ts){
		
	}
}

?>